package com.steve.mac.tools.java8test;

import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * designed by Steve Ke on 2017/12/10.
 *
 * @author Steve Ke
 *         e-mail  huangke7296@foxmail.com
 *         github  https://github.com/KoreHuang
 *         oschina https://git.oschina.net/steveKe
 * @version JDK 1.8.0_111
 * @since 2017/12/10
 */

public class PredicateConsumer {

    /**
     * Predicate和Consumer接口的test()和accept()方法都接受一个泛型参数。
     * 不同的是test()方法进行某些逻辑判断并返回一个boolean值，
     * 而accept()接受并改变某个对象的内部值。
     */

    static class Student {
        String firstName;
        String lastName;
        Double grade;
        Double feeDiscount = 0.0;
        Double baseFee = 20000.0;

        public Student(String firstName, String lastName, Double grade) {

            this.firstName = firstName;

            this.lastName = lastName;

            this.grade = grade;

        }
        public void printFee(){

            Double newFee = baseFee - ((baseFee * feeDiscount) / 100);

            System.out.println("The fee after discount: " + newFee);

        }
    }

    /**
     *
     *  使用Predicate接口实现类的test()方法判断输入的Student对象是否拥有费用打折的资格
     *  然后使用Consumer接口的实现类更新输入的Student对象的折扣
     *
     * @param student
     * @param predicate
     * @param consumer
     * @return
     */
    public static Student updateStudentFee(Student student,
                                           Predicate<Student> predicate,
                                           Consumer<Student> consumer){

        //Use the predicate to decide when to update the discount.

        if ( predicate.test(student)){

            //Use the consumer to update the discount value.

            consumer.accept(student);

        }

        return student;

    }
    public static void main(String[] args) {

        Student student1 = new Student("Ashok","Kumar", 9.0);

        student1 = updateStudentFee(student1,

                //Lambda expression for Predicate interface
                student -> student.grade > 8.5,

                //Lambda expression for Consumer inerface
                student -> student.feeDiscount = 30.0
        );

        student1.printFee();

        Student student2 = new Student("Rajat","Verma", 8.0);

        student2 = updateStudentFee(
                student2,
                student -> student.grade >= 8,
                student -> student.feeDiscount = 20.0
        );

        student2.printFee();

    }


}